package com.htbb.controller.test;

import java.security.SecureRandom;
import java.util.Map;

import javax.crypto.KeyGenerator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.htbb.common.util.security.AESUtil;
import com.htbb.common.util.security.SignUtil;

@Controller
@RequestMapping(value = "v2/testTool")
public class SignAndCryptionTool {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	/**
	 * 非java平台（如c#）与标准接口对接前，向其提供的加解密的密钥须用此方法生成密钥
	 * @param request
	 * @param response
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "getPrivateKey4NonJavaClient")
	public Object getPrivateKey4NonJavaClient(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "password", required = true) String password)
			throws Exception {

		return getKey(password);
	}
	
	private String getKey(String srcKey) {
		try {
			return Base64.encodeBase64String(AESUtil.getKeyBytes(srcKey));
		} catch (Exception e) {
			throw new RuntimeException("生成密钥出现异常 ");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "signAndEncrypt", produces = "application/json;charset=UTF-8")
	public Object signAndEncrypt(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "json", required = true) String json)
			throws Exception {

		String sign = SignUtil.generateSign(json, password, "UTF-8");
		Map<String, Object> jsonMap = JSON.parseObject(json);
		jsonMap.put("sign", sign);
		String jsonW = JSON.toJSONString(jsonMap);
		String postStr = AESUtil.aesEncrypt(jsonW, password, "UTF-8");
		
		logger.info("tool-signAndEncrypt>>>>\n" + "json:" + json + "\npassword:" + password 
				+ "\njsonW:" + jsonW + "\nsign:" + sign + "\naesEncrypt:" + postStr);
		
		return postStr;
	}
	
	@ResponseBody
	@RequestMapping(value = "decrypt", produces = "application/json;charset=UTF-8")
	public Object decrypt(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "model", required = true) String model)
			throws Exception {

		String json = AESUtil.aesDecrypt(model, password, "UTF-8");
		logger.info("tool-decrypt>>>>\n" + "model:" + model + "\npassword:" + password + "\njson:" + json);
		
		return json;
	}
}
